package com.shycloud.mido.member.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.basic.api.entity.BasDictionary;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.homework.api.entity.WeekMain;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.MsgMain;
import com.shycloud.mido.member.api.entity.MsgMemberInfo;
import com.shycloud.mido.member.api.entity.OrgTeacherDetailed;
import com.shycloud.mido.member.api.vo.DelMsgVO;
import com.shycloud.mido.member.api.vo.MsgMainVO;
import com.shycloud.mido.member.service.MemberServiceV2;
import com.shycloud.mido.member.service.MsgMainService;
import com.shycloud.mido.member.service.MsgMemberInfoService;
import com.shycloud.mido.member.service.TeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 消息模块 controller
 *
 * @author nianhua.jiang
 * @date 2021-06-05
 */
@RestController
@AllArgsConstructor
@RequestMapping("/msg")
@Api(tags = "系统消息")
@ApiIgnore
public class MsgController {

	/** 系统消息业务 service */
	private final MsgMainService msgService;
	/** 个人消息业务 service */
	private final MsgMemberInfoService msgMemberInfoService;
	/** 用户模块 service */
	private final MemberServiceV2 memberService;
	/** 个人教师模块 service */
	private final TeacherService teacherService;

	/**
	 * 获取消息列表
	 *
	 * @param type      0-系统 1-家校
	 * @param current   页数
	 * @param size      每页条数
	 * @param title     标题
	 * @param startTime 开始时间
	 * @param endTime   结束时间
	 * @param rangeType 0-全体 1-教师 2-学生
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/6/9 9:39
	 **/
	@ApiOperation(value = "获取消息列表", notes = "移动端只传-current size isApp=1")
	@GetMapping("getMsg")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "type     ", value = "0-系统 1-家校", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "current  ", value = "页数", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "size     ", value = "每页条数", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "title    ", value = "标题", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "endTime  ", value = "结束时间", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "rangeType", value = "0-全体 1-教师 2-学生", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "orgId", value = "机构ID 总部传-0", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "isApp", value = "是否是APP调用（1-APP）", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "mode", value = "消息类型- 0-人工 1-自动 后台管理传 0-人工", paramType = "query", dataType = "String", required = true)
	})
	public R<IPage<MsgMainVO>> getMsg(Integer current, Integer size, String type, String title,
			String startTime, String endTime, String rangeType, Integer orgId, String mode,
			String isApp) {
		return new R<>(msgService.getMsg(new Page<>(current, size), type, title, startTime, endTime, rangeType, orgId, mode, isApp));
	}

	/**
	 * 新增消息
	 *
	 * @param msgMain 消息信息
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/6/8 9:39
	 **/
	@ApiOperation(value = "新增系统消息", notes = "传参为：title,rangeType 0-全体 1-教师 2-学生 ,message,triggerFrom=3(暂定这些)")
	@PostMapping("addMsg")
	public R<String> addMsg(@RequestBody MsgMain msgMain) {
		return new R<>(msgService.addSysMsg(msgMain));
	}

	/**
	 * 删除系统消息
	 *
	 * @param ids 主键 ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/6/8 14:36
	 **/
	@ApiOperation("删除系统消息")
	@PostMapping("delSysMsgByIds")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "ids", value = "主键ID集合，方便以后做全选删除", paramType = "query", dataType = "String", required = true)
	})
	public R<Boolean> delSysMsgByIds(@RequestBody List<String> ids) {
		return new R<>(msgService.removeByIds(ids));
	}


	/**
	 * 新增个人消息
	 *
	 * @param memberInfo 消息体
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/6/8 18:47
	 **/
	@ApiOperation("新增个人消息")
	@PostMapping("sendMsg")
	public R<Boolean> sendMsg(@RequestBody MsgMemberInfo memberInfo) {
		return new R<>(msgMemberInfoService.save(memberInfo));
	}

	/**
	 * 更新已读状态
	 *
	 * @param id         主键 ID
	 * @param readStatus 已读状态 0未读 1已读
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/6/8 11:22
	 **/
	@ApiOperation("更新阅读状态")
	@GetMapping("updReadStatus")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "主键ID", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "readStatus", value = "已读状态 0未读 1已读", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "mode", value = "", paramType = "query", dataType = "String", required = true)
	})
	public R<Boolean> updReadStatus(String id, String readStatus, String mode, String msgMemberInfoId) {

		if (StringUtils.isNotBlank(msgMemberInfoId)) {
			MsgMemberInfo msgMemberInfoMode0 = msgMemberInfoService.getById(msgMemberInfoId);
			msgMemberInfoMode0.setReadStatus(readStatus);
			return new R(msgMemberInfoService.updateById(msgMemberInfoMode0));
		} else {
			MsgMemberInfo msgMemberInfoMode0 = new MsgMemberInfo();
			msgMemberInfoMode0.setMsgId(id);
			msgMemberInfoMode0.setReadStatus(readStatus);
			msgMemberInfoMode0.setToId(SecurityUtils.getMember().getId());
			return new R(msgMemberInfoService.save(msgMemberInfoMode0));
		}

	}

	/**
	 * 删除个人消息
	 *
	 * @param delMsgVOS 主键 ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/6/8 11:28
	 **/
	@ApiOperation("删除个人消息")
	@PostMapping("delMsgByIds")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "ids", value = "主键ID集合，兼容一键清空", paramType = "query", dataType = "String", required = true)
	})
	public R delMsgByIds(@RequestBody Map<String, List<DelMsgVO>> reqMap) {

		List<DelMsgVO> delMsgVOS = reqMap.get("delMsgVOS");

		if (SecurityUtils.getMember() == null) {
			return new R(CommonConstants.FAIL, "请先登录", false);
		}
		//获取用户ID
		String memberId = SecurityUtils.getMember().getId();

		for (DelMsgVO delMsgVO : delMsgVOS) {

			MsgMemberInfo msgMemberInfo = new MsgMemberInfo();

			if (StringUtils.isNotBlank(delMsgVO.getMsgMemberInfoId())) {
				msgMemberInfo = msgMemberInfoService.getById(delMsgVO.getMsgMemberInfoId());
			}

			//删除消息
			msgMemberInfo.setDelFlag(CommonConstants.STATUS_DEL);
			//发送人
			msgMemberInfo.setToId(memberId);
			//发送消息ID
			msgMemberInfo.setMsgId(delMsgVO.getMsgId());
			//时间
			msgMemberInfo.setCreateTime(LocalDateTime.now());

			msgMemberInfoService.saveOrUpdate(msgMemberInfo);
		}

		return new R<>(true);
	}

	@ApiOperation("推送周报消息(feign用)")
	@PostMapping("sendWeekMsg")
	public boolean sendWeekMsg(@RequestBody WeekMain weekMain) {
		return msgMemberInfoService.sendWeekMsg(weekMain);
	}

	@ApiOperation("获取默认系统消息")
	@GetMapping("getDefaultMsg")
	public R getDefaultMsg() {

		List<BasDictionary> defaultMsgs = msgService.getDefaultMsg();

		List<String> resString = defaultMsgs.stream().map(x -> x.getDescription())
				.collect(Collectors.toList());

		List<JSONObject> resList = new ArrayList<>();

		for (String jsonString : resString) {
			JSONObject jsonObj = JSON.parseObject(jsonString);
			if ("1".equals(jsonObj.getString("point"))) {
				//判断是否是教师身份或者未登录的情况
				if (SecurityUtils.getMember() == null) {
					continue;
				} else {
					//判断是否是教师
					OrgTeacherDetailed teacherByMemberId = teacherService.getTeacherByMemberId(SecurityUtils.getMember().getId());
					if (teacherByMemberId != null) {
						continue;
					}
					//判断是否订阅了周报
					Member member = memberService.getById(SecurityUtils.getMember().getId());
					if ("1".equals(member.getSubscribe())) {
						continue;
					}
				}

			}
			resList.add(jsonObj);
		}
		return new R(resList);
	}

}